package com.tianhe.common.tongsuo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;


@Component
@Slf4j
public class SM3JNI {

    static {
        // 先加载依赖库
        //获取操作系统类型
        String osName = System.getProperties().getProperty("os.name").toLowerCase();
        if (osName != null && osName.startsWith("linux")) {
            System.load("/home/gm/lib/libgmjni.so");
        } else if (osName != null && osName.startsWith("windows")) {
            String loadLibrary = System.getProperty("user.dir")  + File.separator+ "sm" + File.separator+"gm"+File.separator+"lib"+File.separator;
            String library = "libgmjni.dll";
            System.out.println(loadLibrary+library);
            System.load(System.getProperty("user.dir") + File.separator+"sm"+ File.separator+"tongsuo"+ File.separator+"bin"+ File.separator+"libcrypto-3-x64.dll");
            System.load(System.getProperty("user.dir") + File.separator+"sm"+ File.separator+"tongsuo"+ File.separator+"bin"+ File.separator+"libssl-3-x64.dll");
            System.load(System.getProperty("user.dir") + File.separator+"sm"+ File.separator+"gm"+ File.separator+"lib"+ File.separator+"libgmjni.dll");
        } else {
            log.info("其他操作系统");
        }
    }


    public native int digest(byte[] msg, byte[] digest);

    public String sm3DigestHex(String input) {
        SM3JNI sm3 = new SM3JNI();
        byte[] msg = input.getBytes();

        byte[] digest = new byte[32];
        System.out.println(System.getProperty("java.library.path"));
        System.out.println("Message: " + new String(msg));
        int result = sm3.digest(msg, digest);
        if (result == 0) {
            StringBuilder sb = new StringBuilder();
            System.out.print("SM3 Digest: ");
            for (byte b : digest) {
                System.out.printf("%02x", b);
                sb.append(String.format("%02x", b));
            }
            System.out.println();
            return sb.toString();
        } else {
            System.err.println("SM3 digest failed.");
            return null;
        }
    }
}
